package com.ChengXiZi.service.impl;

import com.ChengXiZi.constant.MessageConstant;
import com.ChengXiZi.dto.PostAddDTO;
import com.ChengXiZi.dto.PostPageDTO;
import com.ChengXiZi.entity.Community;
import com.ChengXiZi.entity.Post;
import com.ChengXiZi.exception.CommunityNotFoundException;
import com.ChengXiZi.mapper.CommunityMapper;
import com.ChengXiZi.mapper.PostMapper;
import com.ChengXiZi.result.PageResult;
import com.ChengXiZi.service.PostService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;
    @Autowired
    private CommunityMapper communityMapper;

    /**
     * 发帖
     * @param postAddDTO
     * @return
     */
    @Override
    public void posted(PostAddDTO postAddDTO) {

        //查询社区是否存在
        Community community = communityMapper.selectById(postAddDTO.getCommunityId());
        if (community == null) {
            throw new CommunityNotFoundException(MessageConstant.COMMUNITY_NOT_FOUND);
        }

        //构造Post对象
        Post post = new Post();
        BeanUtils.copyProperties(postAddDTO,post);
        //补充post信息
        post.setCreateTime(LocalDateTime.now());
        post.setUpdateTime(LocalDateTime.now());

        //向post表内写入新记录
        postMapper.insert(post);
    }

    /**
     * 分页查询
     * @param postPageDTO
     * @return
     */
    @Override
    public PageResult page(PostPageDTO postPageDTO) {
        PageHelper.startPage(postPageDTO.getPage(), postPageDTO.getPageSize());
        Page<Post> page = postMapper.pageQuery(postPageDTO);

        return new PageResult(page.getTotal(),page.getResult());
    }
}
